package cn.mujiankeji.mbrowser.app

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.appcompat.app.AlertDialog
import androidx.compose.material3.AlertDialog
import com.blankj.utilcode.util.ToastUtils
import io.github.vinceglb.filekit.FileKit
import io.github.vinceglb.filekit.dialogs.init

import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import org.koin.core.logger.Level
import java.io.File
import kotlin.system.exitProcess

class MBrowserApp : Application() {
    private val TAG = "MBrowserApp"

    val ctx = this.baseContext
    var aty : ComponentActivity ?= null


    
    override fun onCreate() {
        super.onCreate()

        Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->

            Handler(Looper.getMainLooper()).post {
                AlertDialog.Builder(aty?:return@post)
                    .setTitle("程序崩溃信息")
                    .setMessage(throwable.message)
                    .setCancelable(false)
                    .setPositiveButton("关闭") { _, _ -> exitProcess(2) }
                    .show()
            }

            // 写到本地文件
            val downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            File(downloadDir, "mbrowser_crash.log").writeText(throwable.stackTraceToString())
            // 你也可以用 Toast 显示
        }


        instance = this

        // 初始化Koin
        startKoin {
            androidLogger(Level.ERROR) // 设置日志级别
            androidContext(this@MBrowserApp) // 提供应用程序上下文
            modules(
                listOf(
                    appModule,      // 应用程序模块
                )
            )
        }
    }

    companion object{
        @SuppressLint("StaticFieldLeak")
        private lateinit var instance : MBrowserApp
        fun init(it : ComponentActivity){
            FileKit.init(it)
            instance.aty = it
        }
        fun ctx() : Context = instance.applicationContext
    }

} 